package com.tuanzi.loan.web.bean.family;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.family.ClassificationInfoView;
import com.tuanzi.loan.business.service.family.ClassificationService;
import com.tuanzi.loan.business.service.family.MemberRightsService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.family.ClassificationInfoSearchRequest;
import com.tuanzi.loan.vo.view.family.ClassificationView;
import com.tuanzi.loan.vo.view.family.MemberRightsView;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.List;

import static com.tuanzi.loan.business.constants.DictionaryCode.ONLINE_OFFLINE_STATUS;

/**
 * @Auther: hequnayu
 * @Date: 2019/4/11 10:16
 * @Description:
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class ClassificationAddBean extends JSFInfoBean<ClassificationInfoView> {

    @Autowired
    private MemberRightsService memberRightsService;

    @Autowired
    private ClassificationService classificationService;

    @PostConstruct
    private void init() {
        String id = getParamFromRequest("id");
        $ = new ClassificationInfoView();
        if (StringUtils.isEmpty(id)) {  //新增
            $.setId(classificationService.getLastId());
            $.setSort(classificationService.getBiggestSort());
            $.setStatus(0);
            changeStatusToAdd();
        }else{ //修改
            ClassificationView classification = classificationService.getClassificationById(Long.parseLong(id));
            BeanUtils.copyProperties(classification,$);
        }
    }

    public String onSave() {
        if (validate() == false) return null;
        try{
            ClassificationInfoSearchRequest request = new ClassificationInfoSearchRequest();
            BeanUtils.copyProperties($,request);
            classificationService.saveClassification(request);
            changeStatusToView();
            addSuccessfullyMessage();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;

    }

    private boolean validate() {
        if(StringUtils.isEmpty($.getClassif_name())){
            addErrorMessage("分类名称不能为空");
            return false;
        }
        if(null == $.getSort()){
            addErrorMessage("分类排序不能为空");
            return false;
        }
        return true;
    }

    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(ONLINE_OFFLINE_STATUS);
    }
}
